package com.example.demo.mysql;

import com.example.demo.config.RedisUtil;
import com.example.demo.mysql.db.UserDB;
import com.example.demo.mysql.mode.DataResult;
import com.example.demo.mysql.mode.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * Created by df on 2018/9/28.
 */
@RestController
public class LoginController {
    private static final Logger log = LoggerFactory.getLogger(LoginController.class);


    @Autowired
    private RedisUtil redisUtil;

@Autowired
private UserDB userDB;


    private int expireTime = 60000;//token过期时间


    @RequestMapping(path = "/login")
    public DataResult login(String account, String password, HttpServletResponse response) throws Exception {
        if(account==null || account == "" || password==null||account==""){
            return new DataResult(StatusCode.USERNAME_PASSWORD_EMPTY);
        }
        try {

            if (userDB.Login(account,password) ) {
                String token = TokenStorage(response, account);
                log.info("登录成功,存储token");
                return new DataResult(StatusCode.LOGIN_OK, token);
            } else {
                log.info("登录失败,用户名或密码错误");
                return new DataResult( StatusCode.PASSWORD_ERROR);
            }
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        return new DataResult(StatusCode.USERNAME_PASSWORD_EMPTY);
    }

    public String TokenStorage(HttpServletResponse response, String account) {
        //生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        userDB.toekn(token,account);
        //存储redis里
        redisUtil.set(token, account, expireTime);
        return token;
    }

}
